package com.shxc.smarttrade.quotation.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.shxc.smarttrade.R;
import com.shxc.smarttrade.account.activity.HelpCenterActivity;
import com.shxc.smarttrade.base.BaseFragment;
import com.shxc.smarttrade.info.Contents;
import com.shxc.smarttrade.login.activity.LoginHomeActivity;
import com.shxc.smarttrade.main.MainActivity;
import com.shxc.smarttrade.quotation.activity.QuotationChooseActivity;
import com.shxc.smarttrade.quotation.adapter.QuotationPagerAdapter;
import com.shxc.smarttrade.quotation.adapter.QuotationRealtimeAdapter;
import com.shxc.smarttrade.quotation.model.BriefModel;
import com.shxc.smarttrade.quotation.model.GetQuotesModel;
import com.shxc.smarttrade.quotation.model.RealTimeQuoteDatas;
import com.shxc.smarttrade.quotation.old.AllQuotationActivity;
import com.shxc.smarttrade.utils.AppUtils;
import com.shxc.smarttrade.utils.MyOkHttpUtils;
import com.shxc.smarttrade.utils.ToastUtils;
import com.shxc.smarttrade.utils.UiUtils;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisModel;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisUtils;

import org.xchris.view.annotation.ContentView;
import org.xchris.view.annotation.Event;
import org.xchris.view.annotation.ViewInject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 行情
 */
@ContentView(R.layout.fragment_quotation)
public class QuotationFragment extends BaseFragment {

    @ViewInject(R.id.right_imageview)
    ImageView right_imageview;//编辑
    @ViewInject(R.id.sourse_textview)
    TextView sourse_textview;//来源
    @ViewInject(R.id.tablayout)
    TabLayout tablayout;
    @ViewInject(R.id.viewpager)
    ViewPager viewpager;
    @ViewInject(R.id.sourse_linearlayout)
    LinearLayout sourse_linearlayout;
    @ViewInject(R.id.add_imageview)
    ImageView add_imageview;

    boolean first = false;
    boolean second = false;
    boolean third = false;
    boolean fourth = false;

    private static final String[] tabName = {"自选", "货币", "商品", "能源", "指数"};
    private List<String> tabTitleList = Arrays.asList(tabName);

    private QuotationPagerAdapter pagerAdapter;

    private List<GetQuotesModel.DataBean.SymbolsBean> qrtlist;
    //自选列表
    private List<GetQuotesModel.DataBean.SymbolsBean> list0;//0 外汇；
    private List<GetQuotesModel.DataBean.SymbolsBean> list1;//1 指数；
    private List<GetQuotesModel.DataBean.SymbolsBean> list2;//2 贵金属；
    private List<GetQuotesModel.DataBean.SymbolsBean> list3;//3 能源,

    private QuotationRealtimeAdapter qrtAdapter;
    private QuotationRealtimeAdapter adapter0;
    private QuotationRealtimeAdapter adapter1;
    private QuotationRealtimeAdapter adapter2;
    private QuotationRealtimeAdapter adapter3;

    private int cur = 0;//滑动页面
    private String symbolchoose = "";//查询自选
    private String symbol0 = "";
    private String symbol1 = "";
    private String symbol2 = "";
    private String symbol3 = "";

    private List<BriefModel> briefModelList = new ArrayList<>();

    MainActivity mainActivity;

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        loadingDialog.setCanceledOnTouchOutside(false);

        mainActivity = (MainActivity) getActivity();

        qrtlist = new ArrayList();
        list0 = new ArrayList();//0 外汇；
        list1 = new ArrayList();//1 指数；
        list2 = new ArrayList();//2 贵金属；
        list3 = new ArrayList();//3 能源,

        add_imageview.setVisibility(View.GONE);
        initViewPagerSet();

    }

    private void initViewPagerSet() {

        viewpager.setOffscreenPageLimit(5);
        qrtAdapter = new QuotationRealtimeAdapter(mContext, qrtlist, handler);
        adapter0 = new QuotationRealtimeAdapter(mContext, list0, handler);
        adapter1 = new QuotationRealtimeAdapter(mContext, list1, handler);
        adapter2 = new QuotationRealtimeAdapter(mContext, list2, handler);
        adapter3 = new QuotationRealtimeAdapter(mContext, list3, handler);

        pagerAdapter = new QuotationPagerAdapter(mInflater, mContext, tabTitleList,
                qrtAdapter, adapter0, adapter1, adapter2, adapter3);
        viewpager.setAdapter(pagerAdapter);

        tablayout.setupWithViewPager(viewpager);
        tablayout.post(new Runnable() {
            @Override
            public void run() {
                UiUtils.setTabLineWidth(tablayout, 15);//字线同宽
            }
        });

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                        cur = position;
                        setTabState();
                        if (position == 0 && !isRefresh) {
                            handler.postDelayed(runnable, 1500);
                        }
                        if (positionOffset == 0) {
                            //未滑动时
                            if (qrtlist.size() == 0 && position == 0) {
                                //数据为空显示+
                                sourse_linearlayout.setVisibility(View.GONE);
                                add_imageview.setVisibility(View.VISIBLE);
                            } else {
                                //不为空显示列表
                                sourse_linearlayout.setVisibility(View.VISIBLE);
                                add_imageview.setVisibility(View.GONE);
                            }
                        } else {
                            //不在自选显示列表
                            sourse_linearlayout.setVisibility(View.VISIBLE);
                            add_imageview.setVisibility(View.GONE);
                        }

                        switch (position) {
                            case 1:
                                if (!first) {
                                    loadingDialog.show();
                                    first = true;
                                }
                                break;
                            case 2:
                                if (!second) {
                                    loadingDialog.show();
                                    second = true;
                                }
                                break;
                            case 3:
                                if (!third) {
                                    loadingDialog.show();
                                    third = true;
                                }
                                break;
                            case 4:
                                if (!fourth) {
                                    loadingDialog.show();
                                    fourth = true;
                                }
                                break;
                        }
                    }

                    @Override
                    public void onPageSelected(int position) {
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {
                    }
                });
            }
        }, 1500);


    }

    @Event({R.id.left_imageview, R.id.right_imageview, R.id.add_imageview})
    private void onClick(View view) {
        switch (view.getId()) {
            case R.id.left_imageview:
                //客服中心
                mainActivity.jumpType = 2;
                JumpTo(HelpCenterActivity.class);
                break;
            case R.id.right_imageview:
            case R.id.add_imageview:
                //编辑
                mainActivity.jumpType = 2;
                if (spImp.getUserId() == -1) {
                    JumpTo(LoginHomeActivity.class);
                } else {
                    bundle.putSerializable("list", (Serializable) briefModelList);
                    JumpTo(QuotationChooseActivity.class, bundle);
                }
                break;
        }
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    //點擊跳轉
                    GetQuotesModel.DataBean.SymbolsBean m3 = (GetQuotesModel.DataBean.SymbolsBean) msg.obj;
                    Intent intent = new Intent(getActivity(), AllQuotationActivity.class);
                    intent.putExtra("symbol", m3.getSymbolEn());
                    intent.putExtra("symbolCn", m3.getSymbolCn());
                    intent.putExtra("tag", 0);
                    intent.putExtra("digits", m3.getDigits());
                    mainActivity.jumpType = 2;
                    startActivity(intent);
//                    MobclickAgent.onEvent(getContext(), "transaction_detail");//友盟统计该点击事件发生次数
                    break;
                case 4:
                    if (qrtlist.size() == 0) {
                        add_imageview.setVisibility(View.VISIBLE);
                        sourse_linearlayout.setVisibility(View.GONE);
                    } else {
                        add_imageview.setVisibility(View.GONE);
                        sourse_linearlayout.setVisibility(View.VISIBLE);
                    }
                    break;
            }
            super.dispatchMessage(msg);
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        loadingDialog.show();
        initDatas();
        getAllSymbol();
        cur = 0;
        viewpager.setCurrentItem(cur);
        setTabState();
        setSourse();
    }

    long exitTime = 0;

    @SuppressLint("NewApi")
    private void setSourse() {

        if ((System.currentTimeMillis() - exitTime) > 1000) {
            exitTime = System.currentTimeMillis();
        }else {
            return;
        }

        if (spImp.getAccType() == 0) {
            sourse_textview.setText(getString(R.string.quotation_sourse0));
            sourse_textview.setCompoundDrawablesWithIntrinsicBounds(
                    getActivity().getResources().getDrawable(R.drawable.st_text_icon, null), null,null, null);
        } else if (spImp.getAccType() == 1) {
            sourse_textview.setText(getString(R.string.quotation_sourse1));
            sourse_textview.setCompoundDrawablesWithIntrinsicBounds(
                    getActivity().getResources().getDrawable(R.drawable.tiger_text_icon, null),null, null, null);
        } else if (spImp.getAccType() == 2) {
            sourse_textview.setText(getString(R.string.quotation_sourse2));
            sourse_textview.setCompoundDrawablesWithIntrinsicBounds(
                    getActivity().getResources().getDrawable(R.mipmap.account_kvb_logo, null), null,null, null);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        handler.removeCallbacks(runnable);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        //不可见，不显示
        if (hidden) {
            handler.removeCallbacks(runnable);
        } else {
            handler.postDelayed(runnable, 1500);
            setSourse();
        }
    }

    //所有品种的当前行情
    public void getAllSymbol() {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", spImp.getUserId());
        MyOkHttpUtils.getServiceDatas(map, Contents.DEAL_SYMBOL_PRICE, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {


                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, GetQuotesModel.class);
                    if (jam.isSuccess()) {

                        GetQuotesModel model = (GetQuotesModel) jam.getData();
                        list0.clear();
                        list1.clear();
                        list2.clear();
                        list3.clear();

                        for (int i = 0; i < model.getData().getSymbols().size(); i++) {
                            GetQuotesModel.DataBean.SymbolsBean symbolsBean = model.getData().getSymbols().get(i);
                            switch (symbolsBean.getGroup()) {
                                case 0:
                                    list0.add(symbolsBean);
                                    break;
                                case 1:
                                    list1.add(symbolsBean);
                                    break;
                                case 2:
                                    list2.add(symbolsBean);
                                    break;
                                case 3:
                                    list3.add(symbolsBean);
                                    break;
                            }
                        }
                        symbol0 = getSymbolStr(list0);
                        symbol1 = getSymbolStr(list1);
                        symbol2 = getSymbolStr(list2);
                        symbol3 = getSymbolStr(list3);
                    } else {
                        ToastUtils.showToast(jam.getMsg());
                    }
                }
                loadingDialog.dismiss();
            }

            @Override
            public void faild(Call call, Exception e, int id) {
                loadingDialog.dismiss();
            }
        });
    }

    //用户关注品种行情
    private void initDatas() {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", spImp.getUserId());

        MyOkHttpUtils.getServiceDatas(map, Contents.DEAL_SYMBOL_FOCUS, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {
                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, GetQuotesModel.class);
                    if (jam.isSuccess()) {
                        GetQuotesModel model = (GetQuotesModel) jam.getData();
                        qrtlist = model.getData().getSymbols();
                        briefModelList.clear();
                        for (int i = 0; i < qrtlist.size(); i++) {
                            if (i == 0) {
                                symbolchoose = qrtlist.get(i).getSymbolEn().replaceAll("\\d+", "");
                            } else {
                                symbolchoose = symbolchoose + "," + qrtlist.get(i).getSymbolEn().replaceAll("\\d+", "");
                            }
                            briefModelList.add(new BriefModel(qrtlist.get(i).getSymbolEn(), qrtlist.get(i).getSymbolCn(), qrtlist.get(i).getGroup() + ""));
                        }
                        handler.sendEmptyMessage(4);
                        qrtAdapter.seList(qrtlist);
                        handler.postDelayed(runnable, 1500);
                    } else {
//                        ToastUtils.showToast(jam.getMsg());
                    }
                }
//                loadingDialog.dismiss();
            }

            @Override
            public void faild(Call call, Exception e, int id) {
//                loadingDialog.dismiss();
            }
        });
    }

    boolean isRefresh = true;

    //获取实时数据
    private void getRealTimeQuoteDatas() {
        Map<String, Object> map = new HashMap<>();
        //根据页面刷新数据
        switch (cur) {
            case 0:
                if (AppUtils.isEmpty(symbolchoose)) {
                    isRefresh = false;
                }
                map.put("symbol", symbolchoose);
                break;
            case 1:
                map.put("symbol", symbol0);
                isRefresh = true;
                break;
            case 2:
                map.put("symbol", symbol2);
                isRefresh = true;
                break;
            case 3:
                map.put("symbol", symbol3);
                isRefresh = true;
                break;
            case 4:
                map.put("symbol", symbol1);
                isRefresh = true;
                break;
        }


        if (isRefresh) {

            MyOkHttpUtils.getServiceDatas(map, Contents.QUOTE_REALTIMEQUOTE, new MyOkHttpUtils.ServiceStatus() {
                @Override
                public void success(String response, int d) {
                    if (response != null) {
                        JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, RealTimeQuoteDatas.class);
                        if (jam.isSuccess()) {
                            RealTimeQuoteDatas rd = (RealTimeQuoteDatas) jam.getData();
                            if (rd.getData().getQuote() != null && rd.getData().getQuote().size() != 0) {
                                switch (cur) {
                                    case 0:
                                        if (rd.getData().getQuote().size() == qrtlist.size()) {
                                            qrtAdapter.setUpdateList(rd.getData().getQuote());
                                        }
                                        break;
                                    case 1:
                                        if (rd.getData().getQuote().size() == list0.size()) {
                                            adapter0.setUpdateList(rd.getData().getQuote());
                                        }
                                        break;
                                    case 2:
                                        if (rd.getData().getQuote().size() == list2.size()) {
                                            adapter2.setUpdateList(rd.getData().getQuote());
                                        }
                                        break;
                                    case 3:
                                        if (rd.getData().getQuote().size() == list3.size()) {
                                            adapter3.setUpdateList(rd.getData().getQuote());
                                        }
                                        break;
                                    case 4:
                                        if (rd.getData().getQuote().size() == list1.size()) {
                                            adapter1.setUpdateList(rd.getData().getQuote());
                                        }
                                        break;
                                }
                                handler.postDelayed(runnable, 1500);
                            }
                        } else {
                        }
                    }
                    loadingDialog.dismiss();
                }

                @Override
                public void faild(Call call, Exception e, int id) {
                    loadingDialog.dismiss();
                }
            });
        }
    }

    //获取实时行情所需查询的字段
    private String getSymbolStr(List<GetQuotesModel.DataBean.SymbolsBean> list) {
        String symbol = "";

        for (int i = 0; i < list.size(); i++) {
            if (i == 0) {
//                symbol = list.get(i).getSymbolEn().replaceAll("\\d+","");
                symbol = list.get(i).getSymbolEn();
            } else {
//                symbol = symbol + "," + list.get(i).getSymbolEn().replaceAll("\\d+","");
                symbol = symbol + "," + list.get(i).getSymbolEn();
            }
        }

        return symbol;
    }

    private long updateTime = 0;
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (updateTime == 0 || System.currentTimeMillis() - updateTime > 999) {
                updateTime = System.currentTimeMillis();
                getRealTimeQuoteDatas();
            }
        }
    };

    //设置Tab状态
    private void setTabState() {
        if (cur == 0) {
            right_imageview.setVisibility(View.VISIBLE);
        } else {
            right_imageview.setVisibility(View.GONE);
        }
    }

    public void JumpTo(Class cla) {
        Intent intent = new Intent(getActivity(), cla);
        startActivity(intent);
    }
}
